//
//  LVLoginMainViewController.m
//  LEVE
//
//  Created by 王若聪 on 2017/2/17.
//  Copyright © 2017年 dashuju. All rights reserved.
//

#import "LVLoginMainViewController.h"
//#import "SVProgressHUD.h"
//#import "NTESLogManager.h"
//#import "NSString+NTES.h"
//#import "NTESLoginManager.h"
#import "UIView+Toast.h"
//#import "NTESService.h"
#import "HYMainViewController.h"
//#import "UIActionSheet+NTESBlock.h"
#import "NSString+Addition.h"
#import "LVForgetPasswordViewController.h"
#import "UIButton+Addition.h"
@interface LVLoginMainViewController ()
@property (strong, nonatomic) UIImageView *usernameIconView;
@property (strong, nonatomic) UIImageView *passwordIconView;
@property (strong, nonatomic) UITextField *usernameTextField;
@property (strong, nonatomic) UITextField *passwordTextField;
@property (strong, nonatomic) UIButton    *usernameTextFieldClearTextBtn;
@property (strong, nonatomic) UIButton    *passwordTextFieldClearTextBtn;
@property (strong, nonatomic) UIButton    *loginBtn;
@property (strong, nonatomic) UIButton    *forgetPasswordBtn;
@end

@implementation LVLoginMainViewController

- (instancetype)init{
    self = [super init];
    if (self) {
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.usernameIconView = [[UIImageView alloc]init];
    self.usernameIconView.size = CGSizeMake(20, 20);
    self.usernameIconView.image = [UIImage imageNamed:@"user name"];
    [self.view addSubview:self.usernameIconView];
    [self.usernameIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@53);
        NSNumber *topValue = kScreenWidth > 320 ? @231 : @131;
        make.top.equalTo(topValue);
    }];
    
    self.passwordIconView = [[UIImageView alloc]init];
    self.passwordIconView.size = CGSizeMake(20, 20);
    self.passwordIconView.image = [UIImage imageNamed:@"password"];
    [self.view addSubview:self.passwordIconView];
    [self.passwordIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.usernameIconView.mas_left);
        make.top.equalTo(self.usernameIconView.mas_bottom).offset(40);
    }];
    
    self.usernameTextField = [[UITextField alloc]init];
    self.usernameTextField.placeholder = @"手机号码/乐无号";
    self.usernameTextField.tintColor = [UIColor grayColor];
    [self.view addSubview:self.usernameTextField];
    [self.usernameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@20);
        make.left.equalTo(self.usernameIconView.mas_left).offset(53);
        make.right.equalTo(self.view).offset(-50);
        make.top.equalTo(self.usernameIconView.mas_top).offset(2);
    }];
    
    self.passwordTextField = [[UITextField alloc]init];
    self.passwordTextField.placeholder = @"登录密码";
    self.passwordTextField.tintColor = [UIColor grayColor];
    [self.view addSubview:self.passwordTextField];
    self.passwordTextField.secureTextEntry = YES;
    [self.passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@20);
        make.left.equalTo(self.passwordIconView.mas_left).offset(53);
        make.right.equalTo(self.view).offset(-50);
        make.top.equalTo(self.passwordIconView.mas_top).offset(2);
    }];
    
    [self.usernameTextField setValue:[UIFont systemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
    [self.passwordTextField setValue:[UIFont systemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
    
    [self.usernameTextField setValue:UIColorFromRGBA(0xA1A7AE, .6f) forKeyPath:@"_placeholderLabel.textColor"];
    [self.passwordTextField setValue:UIColorFromRGBA(0xA1A7AE, .6f) forKeyPath:@"_placeholderLabel.textColor"];
    
    
    self.usernameTextFieldClearTextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.usernameTextFieldClearTextBtn setImage:[UIImage imageNamed:@"btn_delete_default"] forState:UIControlStateNormal];
    [self.usernameTextFieldClearTextBtn setImage:[UIImage imageNamed:@"btn_delete_selected"] forState:UIControlStateNormal];
    [self.usernameTextFieldClearTextBtn addTarget:self action:@selector(usernameTextFieldClearTextBtnTouched) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.usernameTextFieldClearTextBtn];
    [self.usernameTextFieldClearTextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@16);
        make.width.equalTo(@16);
        make.left.equalTo(self.usernameTextField.mas_right).offset(-16);
        make.right.equalTo(self.usernameTextField.mas_right);
        make.bottom.equalTo(self.usernameTextField.mas_bottom);
    }];
    self.usernameTextFieldClearTextBtn.hidden = YES;
    
    self.passwordTextFieldClearTextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.passwordTextFieldClearTextBtn setImage:[UIImage imageNamed:@"btn_delete_default"] forState:UIControlStateNormal];
    [self.usernameTextFieldClearTextBtn setImage:[UIImage imageNamed:@"btn_delete_selected"] forState:UIControlStateNormal];
    [self.passwordTextFieldClearTextBtn addTarget:self action:@selector(passwordTextFieldClearTextBtnTouched) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.passwordTextFieldClearTextBtn];
    [self.passwordTextFieldClearTextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@16);
        make.width.equalTo(@16);
        make.left.equalTo(self.passwordTextField.mas_right).offset(-16);
        make.right.equalTo(self.passwordTextField.mas_right);
        make.bottom.equalTo(self.passwordTextField.mas_bottom);
    }];
    self.passwordTextFieldClearTextBtn.hidden = YES;
    
    UIView *bottomLineView = [[UIView alloc]init];
    bottomLineView.backgroundColor = UIColorFromRGB(0xD7D7D7);
    [self.view addSubview:bottomLineView];
    [bottomLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.usernameTextField.mas_bottom).offset(5);
        make.height.equalTo(@2);
        make.left.equalTo(self.usernameIconView.mas_left);
        make.right.equalTo(self.usernameTextField.mas_right);
    }];
    
    UIView *bottomLineView2 = [[UIView alloc]init];
    bottomLineView2.backgroundColor = UIColorFromRGB(0xD7D7D7);
    [self.view addSubview:bottomLineView2];
    [bottomLineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordTextField.mas_bottom).offset(5);
        make.height.equalTo(@2);
        make.left.equalTo(self.passwordIconView.mas_left);
        make.right.equalTo(self.passwordTextField.mas_right);
    }];
    
    self.loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:22.f];
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [self.loginBtn setBackgroundImage:[self.loginBtn buttonImageWithColor:UIColorFromRGB(0xD0CFCB)] forState:UIControlStateNormal];
    [self.loginBtn setBackgroundImage:[self.loginBtn buttonImageWithColor:UIColorFromRGB(0xFFB32C)] forState:UIControlStateHighlighted];

    [self.loginBtn addTarget:self action:@selector(loginBtnTouched) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginBtn];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@56);
        make.left.equalTo(self.passwordIconView.mas_left);
        make.right.equalTo(self.passwordTextField.mas_right);
        make.top.equalTo(self.passwordTextField.mas_bottom).offset(60);
    }];
    self.loginBtn.layer.cornerRadius = 28;
    self.loginBtn.layer.masksToBounds = YES;
    _loginBtn.enabled = NO;

    
    self.forgetPasswordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.forgetPasswordBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    self.forgetPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:16.f];
    [self.forgetPasswordBtn setTitleColor:UIColorFromRGB(0x9B9B9B) forState:UIControlStateNormal];
    [self.forgetPasswordBtn addTarget:self action:@selector(forgetBtnTouched) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.forgetPasswordBtn];
    [self.forgetPasswordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@40);
        make.left.equalTo(self.loginBtn.mas_left);
        make.right.equalTo(self.loginBtn.mas_right);
        make.top.equalTo(self.loginBtn.mas_bottom).offset(10);
    }];    
    
}

- (void)usernameTextFieldClearTextBtnTouched{
    self.usernameTextField.text = nil;
}

- (void)passwordTextFieldClearTextBtnTouched{
    self.passwordTextField.text = nil;
}
//登录
- (void)loginBtnTouched{
    [_usernameTextField resignFirstResponder];
    _usernameTextFieldClearTextBtn.hidden = YES;
    [_passwordTextField resignFirstResponder];
    _passwordTextFieldClearTextBtn.hidden = YES;
    
    NSString *username = [_usernameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *password = _passwordTextField.text;

    /*
    [SVProgressHUD show];
    
    NSString *loginAccount = username;
    NSString *loginToken   = [password tokenByPassword];
    
    //NIM SDK 只提供消息通道，并不依赖用户业务逻辑，开发者需要为每个APP用户指定一个NIM帐号，NIM只负责验证NIM的帐号即可(在服务器端集成)
    //用户APP的帐号体系和 NIM SDK 并没有直接关系
    //DEMO中使用 username 作为 NIM 的account ，md5(password) 作为 token
    //开发者需要根据自己的实际情况配置自身用户系统和 NIM 用户系统的关系
    
    
    [[[NIMSDK sharedSDK] loginManager] login:loginAccount
                                       token:loginToken
                                  completion:^(NSError *error) {
                                      [SVProgressHUD dismiss];
                                      if (error == nil)
                                      {
                                          LoginData *sdkData = [[LoginData alloc] init];
                                          sdkData.account   = loginAccount;
                                          sdkData.token     = loginToken;
                                          [[NTESLoginManager sharedManager] setCurrentLoginData:sdkData];
                                          
                                          [[NTESServiceManager sharedManager] start];
                                          
                                          HYMainViewController *mainVc = [[HYMainViewController alloc] init];
                                          [UIApplication sharedApplication].keyWindow.rootViewController = mainVc;
                                      }
                                      else
                                      {
//                                          NSString *toast = [NSString stringWithFormat:@"登录失败 code: %zd",error.code];
//                                          [self.view makeToast:toast duration:2.0 position:CSToastPositionCenter];
                                          
                                          UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号或密码错误，请重新填写。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                                          [alertView show];
                                      }
                                  }];

    */
}
- (void)forgetBtnTouched{
    //跳转到忘记密码界面
    LVForgetPasswordViewController *vc= [[LVForgetPasswordViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];

}

#pragma mark - Notification
- (void)keyboardWillShow:(NSNotification*)notification{

    
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [self loginBtnTouched];
        return NO;
    }
    return YES;
}

- (void)textFieldDidChange:(NSNotification*)notification{
    
    if ([self.usernameTextField.text length]) {
        self.usernameTextFieldClearTextBtn.hidden = NO;
    }else{
        self.usernameTextFieldClearTextBtn.hidden = YES;
    }
    
    if ([self.passwordTextField.text length]) {
        self.passwordTextFieldClearTextBtn.hidden = NO;
    }else{
        self.passwordTextFieldClearTextBtn.hidden = YES;
    }
    
    if ([self.usernameTextField.text length] && [self.passwordTextField.text length])
    {
        _loginBtn.enabled = YES;
        [self.loginBtn setBackgroundImage:[self.loginBtn buttonImageWithColor:UIColorFromRGB(0xFFCD00)] forState:UIControlStateNormal];

    }else{
        _loginBtn.enabled = NO;
        [self.loginBtn setBackgroundImage:[self.loginBtn buttonImageWithColor:UIColorFromRGB(0xD0CFCB)] forState:UIControlStateNormal];
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if ([self.usernameTextField.text length] && [self.passwordTextField.text length])
    {
        _loginBtn.enabled = YES;
        [self.loginBtn setBackgroundImage:[self.loginBtn buttonImageWithColor:UIColorFromRGB(0xFFCD00)] forState:UIControlStateNormal];

    }else{
        _loginBtn.enabled = NO;
        [self.loginBtn setBackgroundImage:[self.loginBtn buttonImageWithColor:UIColorFromRGB(0xD0CFCB)] forState:UIControlStateNormal];
    }
}

#pragma mark - NTESRegisterViewControllerDelegate
- (void)registDidComplete:(NSString *)account password:(NSString *)password{
    if (account.length) {
        self.usernameTextField.text = account;
        self.passwordTextField.text = password;
        _loginBtn.enabled = YES;
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    [_usernameTextField resignFirstResponder];
    _usernameTextFieldClearTextBtn.hidden = YES;
    [_passwordTextField resignFirstResponder];
    _passwordTextFieldClearTextBtn.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
